﻿using _12Net8AspNetCore_MVC.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace _12Net8AspNetCore_MVC.Controllers
{
    /// <summary>
    /// 商品控制器
    /// </summary>
    public class ProductController:Controller
    {
        static List<Product> products = new List<Product>();
        /// <summary>
        /// 访问Index.cshtml 视图
        /// </summary>
        public ViewResult Index()
        {
            #region 视图返回
            // 1、返回视图结果
            //ViewResult viewResult = new ViewResult();
            //viewResult.ViewName = "Index";
            //return viewResult;
            #endregion

            #region 对象视图返回
            //Product product = new Product();
            //product.ID = 1;
            //product.Name = "MVC";

            //// 1、返回视图结果
            //ViewResult viewResult = new ViewResult();
            //viewResult.ViewName = "Index";
            //viewResult.ViewData = new Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary(new EmptyModelMetadataProvider(),
            //    new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary());
            ////1.1 商品赋值
            //viewResult.ViewData.Model = product;
            //return viewResult;
            #endregion


            #region 集合对象视图返回
            if (products.Count() == 0)
            {
                products.Add(new Product() { ID = 1, Name = "MVC" });
                products.Add(new Product() { ID = 2, Name = "WebAPI" });
            }


            // 1、返回视图结果
            ViewResult viewResult = new ViewResult();
            viewResult.ViewName = "Index";
            viewResult.ViewData = new Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary(new EmptyModelMetadataProvider(),
                new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary());
            //1.1 商品赋值
            viewResult.ViewData.Model = products;
            return viewResult;
            #endregion
        }

        public IActionResult Create()
        {
            return View("Create");
        }

        [HttpPost]
        public IActionResult Create(Product product)
        {
            products.Add(product);
            return RedirectToAction("Index");
        }
    }
}
